﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kxcxw.Data;
using System.Collections;
using kxcxw.Data.Entities;
using System.Web.Security;
using System.IO;
using kxcxw.Business;
using System.Xml;
using System.Xml.Linq;
using System.Text;
using Webdiyer.WebControls.Mvc;
using KXCXW.Web.CommonClass;
using kxcxw.Data.Common;
using System.Data;
using KXCXW.Web.Models;
using System.Web.Caching;

namespace KXCXW.Web.Controllers
{
    public class ActivityController : Controller
    {
        private KXCXWDBContext db = new KXCXWDBContext();

        //
        // GET: /Activity/

        [Authorize]
        public ActionResult MyActivity(string sortOrder, string searchString, int? type, int? page = 1)
        {
            ViewData["dlCount"] = "0";
            ViewData["type"] = type;

            #region 我的信息
            string userid = Membership.GetUser().ProviderUserKey.ToString();
            ViewBag.DateSortParm = sortOrder == "Date" ? "Date desc" : "Date";
            var activity = from s in db.Activitys where s.UserID == userid && s.ShopType == (type == null ? 1 : type) select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                activity = activity.Where(s => s.Title.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "Date":
                    activity = activity.OrderBy(s => s.CreateDate);
                    break;
                default:
                    activity = activity.OrderByDescending(s => s.CreateDate);
                    break;
            }
            int pageSize = 10;
            int pageIndex = page ?? 1;
            PagedList<Activity> temp = activity.ToPagedList(pageIndex, pageSize);
            if (Request.IsAjaxRequest())
                return PartialView("List", temp);
            #endregion
            return View(temp);
        }

        //
        // GET: /Activity/Details/5

        public ViewResult Details(string id)
        {
            Activity activity = db.Activitys.Find(id);
            return View(activity);
        }

        //
        // GET: /Activity/Create

        [Authorize]
        public ActionResult Create(string id)
        {
            ViewBag.ShopType = (id == "2" ? "实体店" : "网店");
            Activity activity = new Activity();
            activity.ActivityId = Guid.NewGuid().ToString();
            activity.ShopUrl = "http://";
            activity.Status = 1;
            activity.ShopType = Convert.ToInt32(id);
            activity.CreateDate = DateTime.Now;
            MembershipUser user = Membership.GetUser();
            activity.UserID = user.ProviderUserKey.ToString();
            return View(activity);
        }

        //
        // POST: /Activity/Create

        [Authorize]
        [HttpPost]
        public ActionResult Create(Activity activity)
        {
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file = Request.Files["ImageName"];
                if (file != null)
                {
                    try
                    {
                        string fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                        if (ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/Content/upload/Activity/img_135_90/"), fileName, 135, 90, file)!="" && ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/Content/upload/Activity/img_270_180/"), fileName, 270, 180, file)!="")
                        {
                            activity.CreateDate = DateTime.Now;
                            activity.ImageName = fileName;
                            if (activity.StartDate == null)
                                activity.StartDate = DateTime.Now;
                            if (activity.EndDate == null)
                                activity.EndDate = DateTime.Now.AddDays(DataConstants.ExpirationDay);
                            db.Activitys.Add(activity);
                            db.SaveChanges();
                            return RedirectToAction("Success", new { id = activity.ShopType });
                        }
                        else
                        {
                            ModelState.AddModelError("file", "图片上传失败！");
                        }
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("exception", "出现异常！");
                    }
                }
            }
            return View(activity);
        }

        //
        // GET: /Activity/Edit/5

        public ActionResult Success(string id)
        {
            ViewBag.ShopType = id;
            return View();
        }
        [Authorize]
        public ActionResult Edit(string id)
        {
            Activity activity = db.Activitys.Find(id);
            return View(activity);
        }

        //
        // POST: /Activity/Edit/5

        [Authorize]
        [HttpPost]
        public ActionResult Edit(Activity activity)
        {
            if (ModelState.IsValid)
            {
                HttpPostedFileBase file = Request.Files["ImageName"];
                string fileName = "";
                try
                {
                    if (file != null && file.FileName != "")
                    {
                        fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
                        if (ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/Content/upload/Activity/img_135_90/"), fileName, 135, 90, file)!="" && ImgUpLoadHelper.SavePicFormat(Server.MapPath("~/Content/upload/Activity/img_270_180/"), fileName, 270, 180, file)!="")
                        {
                            activity.ImageName = fileName;
                        }
                        else
                        {
                            ModelState.AddModelError("file", "图片上传失败！");
                        }
                    }

                    activity.Status = DataConstants.pending;
                    db.Entry(activity).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("EditSuccess", new { id = activity.ShopType });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("exception", "出现异常！");
                }
            }
            return View(activity);
        }


        public ActionResult EditSuccess(string id)
        {
            ViewBag.ShopType = id;
            return View();
        }

        //
        // GET: /Activity/Delete/5
        [Authorize]
        public ActionResult Delete(string id, string searchString, string sortOrder, int page)
        {
            Activity activity = (from q in db.Activitys
                                 where q.ActivityId == id
                                 select q).FirstOrDefault();
            activity.Status = DataConstants.Deleted;
            db.Entry(activity).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("MyActivity", new { type = activity.ShopType, sortOrder = sortOrder, searchString = searchString, page = page });
        }

        //
        // POST: /Activity/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            Activity activity = db.Activitys.Find(id);
            db.Activitys.Remove(activity);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}